package com.yichen.rent.service;

import com.yichen.rent.pojo.Contract;
import com.yichen.rent.utils.PathUtils;
import com.yichen.rent.utils.PdfUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class PdfService {

    @Autowired
    private ContractService contractService;

    public ResponseEntity<byte[]> generatePDFFileTwo(String contractId, HttpServletResponse response) throws Exception {

        //pdf模板相对路径
        String pdfModelPath = PathUtils.getPDFModelPath();
        //pdf临时文件相对路径
        String pdfTempPath = PathUtils.getPDFTempPath();
        //pdf合并文件相对路径
        String pdfExportPath = PathUtils.getPDFExportPath();
        Contract contract = contractService.findById(contractId);
        List<String> stringAllList = new ArrayList<>();
        //循环遍历文件夹下的文件
        List<String> dirlist = PdfUtils.findDir(pdfModelPath + "");
        for (int a = 0; a < dirlist.size(); a++) {
            String path = dirlist.get(a);
            File file = new File(path);
            String fileName = file.getName();
            if (("房屋租赁合同.pdf").equals(fileName)) {
                String textFromPage = PdfUtils.readPdf(path);


                String t01 = textFromPage.replaceAll("0001", contract.getId());
                String t02 = t01.replaceAll("0002", contract.getHouse_id());
                String t03 = t02.replaceAll("0003", contract.getBroker_name());
                String t04 = t03.replaceAll("0004", contract.getBname());
                String t05 = t04.replaceAll("0005", contract.getStart_date());
                String t06 = t05.replaceAll("0006", contract.getEnd_date());
                String t07 = t06.replaceAll("0007", contract.getContent());
                byte[] bytes = t07.getBytes();
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.setContentDispositionFormData("attachment",
                        new String("房屋租赁合同.doc".getBytes("UTF-8"), "iso-8859-1"));
                httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                return new ResponseEntity<byte[]>(bytes, httpHeaders, HttpStatus.CREATED);
            }

        }
        return null;
    }
}